import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_common_ui/flutter_common_ui.dart';

typedef SliderValueFormat = String Function(double value);

class SliderWidget extends StatefulWidget {
  final String title;
  final double value;
  final double min;
  final double max;
  final SliderValueFormat? minFormat;
  final SliderValueFormat? maxFormat;
  final SliderValueFormat? labelFormat;

  // 是否自动计算小数点位数
  final int decimalNumber;

  //整体高度
  final double height;

  //轨道高度
  final double trackHeight;

  //滑块半径
  final double thumbRadius;

  // 滑块是否显示数字进度
  final bool isThumbNumber;

  //强制气泡显示
  final bool bubbleActive;

  //  是否可用
  final bool enable;

  // 分段数量
  final int? divisions;
  final bool labelIsShow;

  //颜色
  final Color? color;
  final Color? inactiveColor;
  final ValueChanged<double>? onChanged;
  final ValueChanged<double>? onChangedEnd;
  final String svgAssets;

  const SliderWidget({
    super.key,
    this.title = "",
    required this.value,
    this.color,
    this.inactiveColor,
    this.min = 0,
    this.max = 100,
    this.height = 80,
    this.trackHeight = 4,
    this.thumbRadius = 10,
    this.bubbleActive = false,
    this.isThumbNumber = false,
    this.enable = true,
    this.labelIsShow = false,
    this.decimalNumber = 0,
    this.divisions,
    this.onChanged,
    this.onChangedEnd,
    this.minFormat,
    this.maxFormat,
    this.labelFormat,
    this.svgAssets = "assets/svg/main_ic_bubble.svg",
  });

  @override
  State<StatefulWidget> createState() => _SliderWidgetState();
}

class _SliderWidgetState extends State<SliderWidget> with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  final GlobalKey _sliderKey = GlobalKey();
  double _value = 0.0;

  //气泡大小
  double bubbleSize = 30.0;
  bool isChange = false;

  //滑块中心点
  Offset thumbCenter = Offset.zero;

  //气泡是否显示
  bool showBubble = false;
  late AnimationController _bubbleController;
  late Animation<double> _bubbleOpacityAnimation;
  late Animation<double> _bubbleScaleAnimation;
  late SliderValueFormat _defaultFormat;

  Color get _color => widget.color ?? Theme.of(context).primaryColor;

  Color get _inactiveColor => widget.inactiveColor ?? Color(0xFF929292);

  @override
  void initState() {
    super.initState();
    _defaultFormat = (double value) {
      if (widget.decimalNumber == 0) {
        return value.round().toString();
      } else {
        //保留几位小数
        return value.toStringAsFixed(widget.decimalNumber);
      }
    };
    _bubbleController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 200),
    );
    // 配置动画曲线
    _bubbleOpacityAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _bubbleController,
        curve: Curves.easeInOut,
      ),
    );

    _bubbleScaleAnimation = Tween<double>(begin: 0.2, end: 1.0).animate(
      CurvedAnimation(
        parent: _bubbleController,
        curve: Curves.easeInOutBack,
      ),
    );

    _value = widget.value;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _updateThumbPosition();
      if (widget.bubbleActive) {
        setState(() {
          _handleBubbleVisibility(true);
        });
      }
    });
    WidgetsBinding.instance.addObserver(this);
  }

  // 监听窗口尺寸变化
  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    // 使用 addPostFrameCallback 确保在布局完成后获取正确的位置
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        _updateThumbPosition();
        setState(() {});
      }
    });
  }

  @override
  void didUpdateWidget(SliderWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.value != widget.value) {
      // 同步外部值到内部状态
      _value = widget.value;
      //更新坐标
      _updateThumbPosition();
    }
    if (oldWidget.min != widget.min || oldWidget.max != widget.max) {
      //更新坐标
      _updateThumbPosition();
    }
    if (oldWidget.bubbleActive != widget.bubbleActive) {
      if (widget.bubbleActive) {
        _handleBubbleVisibility(true);
      } else {
        _handleBubbleVisibility(false);
      }
    }
  }

  @override
  void dispose() {
    _bubbleController.dispose();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  // 计算滑块位置
  void _updateThumbPosition() {
    final renderBox = _sliderKey.currentContext?.findRenderObject() as RenderBox?;
    if (renderBox == null) return;
    final width = renderBox.size.width - widget.thumbRadius * 2;
    final height = renderBox.size.height;
    //比例
    final ratio = (_value - widget.min) / (widget.max - widget.min);
    var dx = ratio * width + widget.thumbRadius;
    if (widget.divisions != null) {
      // 分段后需要加上一些轨道高度的值，不然中间值位置是对的，前后值位置不对
      if (ratio < 0.5) {
        dx += (0.5 - ratio) * widget.trackHeight;
      } else if (ratio > 0.5) {
        dx -= (ratio - 0.5) * widget.trackHeight;
      }
    }
    // return renderBox.localToGlobal(Offset(dx, 0)).dx;
    thumbCenter = Offset(dx, height / 2);
    // LogUtils.e("_updateThumbPosition ,,,thumbCenter = $thumbCenter");
  }

  // 判断坐标是否在滑块范围内
  bool _isHoveringThumb(Offset position) {
    final thumbRect = Rect.fromCircle(
      center: thumbCenter,
      radius: widget.thumbRadius + widget.thumbRadius, // 增加热区容差
    );
    // LogUtils.e("_isHoveringThumb ,,,thumbRect=$thumbRect,,,position=$position,,contains = ${thumbRect.contains(position)}");
    return thumbRect.contains(position);
  }

  // 修改状态变化时的动画控制
  bool _handleBubbleVisibility(bool visible) {
    if (widget.bubbleActive) {
      if (!showBubble) {
        showBubble = true;
        _bubbleController.forward();
        return true;
      }
      return false;
    }
    if (visible != showBubble) {
      showBubble = visible;
      if (visible) {
        _bubbleController.forward();
      } else {
        _bubbleController.reverse();
      }
      return true;
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      // color: Colors.yellow,
      height: widget.height,
      child: MouseRegion(
        onHover: (event) {
          if (!isChange) {
            if (_handleBubbleVisibility(_isHoveringThumb(event.localPosition))) setState(() {});
          }
        },
        onExit: (event) {
          if (!isChange) {
            if (_handleBubbleVisibility(false)) setState(() {});
          }
        },
        child: Stack(
          clipBehavior: Clip.none, // 允许子组件溢出
          children: [
            //标题
            if (widget.title.isNotEmpty)
              Positioned(
                left: 10,
                top: 5,
                child: Text(
                  widget.title,
                  style: const TextStyle(fontSize: 12),
                  textAlign: TextAlign.center,
                ),
              ),
            //气泡
            _buildBubble(),
            //滑块
            SliderTheme(
              data: SliderThemeData(
                trackHeight: widget.trackHeight,
                disabledActiveTrackColor: _inactiveColor,
                disabledThumbColor: _inactiveColor,
                showValueIndicator: widget.labelIsShow ? ShowValueIndicator.always : ShowValueIndicator.never,
                padding: EdgeInsets.zero,
                trackGap: 0,
                // 消除滑轨左侧缩进
                // thumbShape: RoundSliderThumbShape(
                //   // 滑块半径
                //   enabledThumbRadius: enabledThumbRadius,
                // ),
                // thumbSize: WidgetStatePropertyAll(Size(widget.thumbRadius * 2, widget.thumbRadius * 2)),
                thumbShape: !widget.isThumbNumber
                    ? RoundSliderThumbShape(enabledThumbRadius: widget.thumbRadius)
                    // 应用自定义滑块
                    : CustomThumbShape(enabledThumbRadius: widget.thumbRadius),
              ),
              child: Slider(
                key: _sliderKey,
                value: _value,
                min: widget.min,
                max: widget.max,
                divisions: widget.divisions,
                inactiveColor: _inactiveColor,
                label: (widget.labelFormat ?? _defaultFormat)(_value),
                padding: EdgeInsets.all(widget.thumbRadius),
                activeColor: _color,
                thumbColor: _color,
                onChangeStart: !widget.enable
                    ? null
                    : (it) {
                        isChange = true;
                        _updateThumbPosition();
                        _handleBubbleVisibility(true);
                        setState(() {});
                      },
                onChangeEnd: !widget.enable
                    ? null
                    : (it) {
                        isChange = false;
                        if (_handleBubbleVisibility(false)) setState(() {});
                        widget.onChangedEnd?.call(it);
                      },
                onChanged: !widget.enable
                    ? null
                    : (it) {
                        _value = it;
                        _updateThumbPosition();
                        setState(() {});
                        widget.onChanged?.call(it);
                      },
              ),
            ),
            //最小值
            Positioned(
              left: widget.thumbRadius,
              bottom: 5,
              child: Text((widget.minFormat ?? _defaultFormat)(widget.min)),
            ),
            //最大值
            Positioned(
              right: widget.thumbRadius,
              bottom: 5,
              child: Text((widget.maxFormat ?? _defaultFormat)(widget.max)),
            )
          ],
        ),
      ),
    );
  }

  //气泡
  Widget _buildBubble() => Positioned(
        left: thumbCenter.dx - bubbleSize / 2,
        top: 0,
        child: AnimatedBuilder(
          animation: _bubbleController,
          builder: (_, child) {
            return Opacity(
              opacity: _bubbleOpacityAnimation.value,
              child: Transform.scale(
                scale: _bubbleScaleAnimation.value,
                child: child,
              ),
            );
          },
          child: SizedBox(
            width: bubbleSize,
            height: bubbleSize,
            child: Stack(
              children: [
                SvgWidget(widget.svgAssets, width: bubbleSize, color: widget.enable ? _color : _inactiveColor),
                Positioned(
                  left: 0,
                  right: 0,
                  top: 2,
                  child: Text(
                    (widget.labelFormat ?? _defaultFormat)(_value),
                    style: const TextStyle(color: Colors.white, fontSize: 12),
                    textAlign: TextAlign.center,
                  ),
                )
              ],
            ),
          ),
        ),
      );
}

//自己绘制滑块
class CustomThumbShape extends SliderComponentShape {
  final double enabledThumbRadius;

  CustomThumbShape({required this.enabledThumbRadius});

  @override
  void paint(
    PaintingContext context,
    Offset center, {
    required Animation<double> activationAnimation,
    required Animation<double> enableAnimation,
    required bool isDiscrete,
    required TextPainter labelPainter,
    required RenderBox parentBox,
    required SliderThemeData sliderTheme,
    required TextDirection textDirection,
    required double value,
    required double textScaleFactor,
    required Size sizeWithOverflow,
  }) {
    // LogUtils.e("ddddddd${center}");
    final Canvas canvas = context.canvas;
    // 绘制圆形滑块
    final Paint thumbPaint = Paint()..color = sliderTheme.thumbColor!;
    canvas.drawCircle(center, enabledThumbRadius, thumbPaint);

    TextSpan labelSpan = labelPainter.text as TextSpan;
    // 绘制文本
    TextSpan textSpan = TextSpan(
      // text: value.toStringAsFixed(0),
      text: labelSpan.text,
      style: const TextStyle(
        color: Colors.white,
        fontSize: 10,
        fontWeight: FontWeight.bold,
      ),
    );

    TextPainter textPainter = TextPainter(
      text: textSpan,
      textDirection: TextDirection.ltr,
    )..layout();
    // 计算文本位置（滑块正上方）
    Offset textOffset = Offset(
      center.dx - textPainter.width / 2,
      center.dy - textPainter.height / 2 - textPainter.height / 10,
    );
    textPainter.paint(canvas, textOffset);
  }

  @override
  Size getPreferredSize(bool isEnabled, bool isDiscrete) {
    return Size(enabledThumbRadius, enabledThumbRadius);
  }
}
